<?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
class UserController extends AdminbaseController{
	protected $users_model,$role_model,$role_user_model;

	function _initialize() {
		parent::_initialize();
		$this->users_model = D("Common/Users");
		$this->role_model = D("Common/Role");
		$this->role_user_model = M("RoleUser");
	}
	function index(){
		if(!get_current_adminug_id() && get_current_adminrole_id() > 9){
            $search[] = array('id'=>get_current_admin_id());
            $_GET['id'] = get_current_admin_id();
		}elseif(get_current_adminug_id() && get_current_adminrole_id() > 9){
            $search[] = array('ugid'=>get_current_adminug_id());
			$usergroups = D("UserGroup")->where(array('parentid'=>get_current_adminug_id()))->select();
            if($usergroups){
				foreach($usergroups as$k=>$ugs){
					$ugroups[$k]=$ugs['id'];
				}
            	$search[] = array('ugid',array('in',$ugroups));
            }
            $_GET['ugid'] = get_current_adminug_id();
		}

		$search[] =array("user_type"=>1);

		$page = $this->page($count, 50);
		$users = $this->users_model
			->join('LEFT JOIN yy_role_user ON yy_role_user.user_id = yy_users.id')
			->join('LEFT JOIN yy_role ON yy_role.id = yy_role_user.role_id')
			->where($search)
			->field('yy_users.*, yy_role.name as role_name')
			->order("create_time DESC")
			->limit($page->firstRow . ',' . $page->listRows)
			->select();

		$roles_src=$this->role_model->select();
		$roles=array();
		foreach ($roles_src as $r){
			$roleid=$r['id'];
			$roles["$roleid"]=$r;
		}
		$this->assign("page", $page->show('Admin'));
		$this->assign("roles",$roles);
		$this->assign("users",$users);
		$this->display();
	}


	function add(){
		if(!get_current_adminug_id() && get_current_adminrole_id() > 9){
            $search[] = array('id'=>array('gt',get_current_adminrole_id()));
            $_GET['id'] = get_current_adminrole_id();
		}elseif(get_current_adminug_id() && get_current_adminrole_id() > 9){
            $search[] = array('id'=>array('gt',get_current_adminrole_id()));
            $_GET['id'] = get_current_adminrole_id();
		}
		$search[] =array("status"=>1);
		$roles=$this->role_model->where($search)->order("id desc")->select();
		$this->assign("roles",$roles);
		$this->display();
	}

	function add_post(){
		if(IS_POST){
			if(!get_current_adminug_id() && get_current_adminrole_id() > 9){
				$this->error("您不属于任何组，请先创建组");
			}elseif(get_current_adminug_id() && get_current_adminrole_id() > 9){
				$_POST['ugid'] =get_current_adminug_id();
			}
			if(!empty($_POST['role_id']) && is_array($_POST['role_id'])){
				$role_ids=$_POST['role_id'];
				unset($_POST['role_id']);
				if ($this->users_model->create()) {
					$result=$this->users_model->add();
					if ($result!==false) {
						$role_user_model=M("RoleUser");
						foreach ($role_ids as $role_id){
							if(get_current_admin_id() != 1 && $role_id == 1){
								$this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
							}
							$role_user_model->add(array("role_id"=>$role_id,"user_id"=>$result));
						}
						$this->success("添加成功！", U("user/index"));
					} else {
						$this->error("添加失败！");
					}
				} else {
					$this->error($this->users_model->getError());
				}
			}else{
				$this->error("请为此用户指定角色！");
			}

		}
	}


	function edit(){
		$id= intval(I("get.id"));
		if(!get_current_adminug_id() && get_current_adminrole_id() > 9){
            $search[] = array('id'=>array('gt',get_current_adminrole_id()));
            $_GET['id'] = get_current_adminrole_id();
		}elseif(get_current_adminug_id() && get_current_adminrole_id() > 9){
            $search[] = array('id'=>array('gt',get_current_adminrole_id()));
            $_GET['id'] = get_current_adminrole_id();
		}
		$search[] =array("status"=>1);
		$roles=$this->role_model->where($search)->order("id desc")->select();
		$this->assign("roles",$roles);
		$role_user_model=M("RoleUser");
		$role_ids=$role_user_model->where(array("user_id"=>$id))->getField("role_id",true);
		$this->assign("role_ids",$role_ids);

		$user=$this->users_model->where(array("id"=>$id))->find();
		$this->assign($user);
		$this->display();
	}

	function edit_post(){
		if (IS_POST) {
			if(!empty($_POST['role_id']) && is_array($_POST['role_id'])){
				if(empty($_POST['user_pass'])){
					unset($_POST['user_pass']);
				}
				$role_ids=$_POST['role_id'];
				unset($_POST['role_id']);
				if ($this->users_model->create()) {
					$result=$this->users_model->save();
					if ($result!==false) {
						$uid=intval($_POST['id']);
						$role_user_model=M("RoleUser");
						$role_user_model->where(array("user_id"=>$uid))->delete();
						foreach ($role_ids as $role_id){
							if(get_current_admin_id() != 1 && $role_id == 1){
								$this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
							}
							$role_user_model->add(array("role_id"=>$role_id,"user_id"=>$uid));
						}
						$this->success("保存成功！");
					} else {
						$this->error("保存失败！");
					}
				} else {
					$this->error($this->users_model->getError());
				}
			}else{
				$this->error("请为此用户指定角色！");
			}

		}
	}

	/**
	 *  删除
	 */
	function delete(){
		$id = intval(I("get.id"));
		if($id==1){
			$this->error("最高管理员不能删除！");
		}

		if ($this->users_model->where("id=$id")->delete()!==false) {
			M("RoleUser")->where(array("user_id"=>$id))->delete();
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}

	function userinfo(){
		$id=get_current_admin_id();
		$user = $this->users_model->where(array("id"=>$id))->find();
		$urole = $this->role_user_model->where(array('user_id'=>$id))->find();
		$role=$this->role_model->where(array('id'=>$urole['role_id']))->find();
		$this->assign("role",$role);
		$this->assign("user",$user);
		$this->assign("urlimg", C('IMG_PATH'));
		$this->display();
	}

	function userinfo_post(){
		if (IS_POST) {
			$_POST['id']=get_current_admin_id();
			$create_result=$this->users_model
			->field("user_login,last_login_ip,last_login_time,create_time,user_activation_key,user_status,role_id,score,user_type",true)//排除相关字段
			->create();
			if ($create_result) {
					if($_FILES){
						$Aliyun = new \Aliyun\Controller\AliyunController();
		                if (!empty($_POST['avatar'])) {
							$Aliyun->delete($_POST['avatar']);
						}
						$imgs = $Aliyun->save($_FILES["newavatar"],'img/'.CONTROLLER_NAME,0,128);
						if(!$_FILES['error']){
							$_POST['avatar'] =$imgs['path'].$imgs['name'];
						}else{
							$this->error('图像上传失败');
						}
					}
				$users = $this->users_model->save($_POST);
				if ($users!==false) {
					$this->success("保存成功！");
				} else {
					$this->error("保存失败！");
				}
			} else {
				$this->error($this->users_model->getError());
			}
		}
	}

	    function ban(){
        $id=intval($_GET['id']);
    	if ($id) {
    		$rst = $this->users_model->where(array("id"=>$id,"user_type"=>1))->setField('user_status','0');
    		if ($rst) {
    			$this->success("管理员停用成功！", U("user/index"));
    		} else {
    			$this->error('管理员停用失败！');
    		}
    	} else {
    		$this->error('数据传入失败！');
    	}
    }

    function cancelban(){
    	$id=intval($_GET['id']);
    	if ($id) {
    		$rst = $this->users_model->where(array("id"=>$id,"user_type"=>1))->setField('user_status','1');
    		if ($rst) {
    			$this->success("管理员启用成功！", U("user/index"));
    		} else {
    			$this->error('管理员启用失败！');
    		}
    	} else {
    		$this->error('数据传入失败！');
    	}
    }



}